<template>
  <div>
    <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :before-upload="beforeUpload"
      @change="handleChange">
      <img style="width: 100%" v-if="imageUrl" :src="imageUrl" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
  </div>
</template>

<script>
  import {
    uuid
  } from "vue-uuid";
  import ObsClient from "esdk-obs-browserjs/src/obs";
  export default {
    data() {
      return {
        filename: '',
        imageUrl: '',
        loading: false
      }
    },
    mounted() {
      let date = new Date()
      this.filename = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    },
    methods: {
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
      },
      beforeUpload(file) {
        // this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        let that = this
        if (isJpgOrPng && isLt2M) {
          let uuids = Date.now() + file.name;
          var obsClient = new ObsClient({
            access_key_id: "GD8AFFQVWU2ECR7IGPXF",
            secret_access_key: "6hLkovv2AhMaOk17y8a7sSp42BYh8EZKtkqkyWhE",
            server: "https://obs.cn-south-1.myhuaweicloud.com"
          });
          obsClient.putObject({
              Bucket: "jiaoyixunfang",
              Key: that.filename + '/' + uuids,
              SourceFile: file,
            },
            function(err, result) {
              if (err) {
                // that.handleUploadError();
              } else {
                that.imageUrl = 'https://jiaoyixunfang.obs.cn-south-1.myhuaweicloud.com/' + that.filename + '/' +
                  uuids
                that.loading = false
                that.$emit('success', that.imageUrl)
              }
            }
          );
        }
      },
    }
  }
</script>

<style>
</style>